package hieuph.facerecognition.mainUi;

import hieuph.facerecognition.FaceDetect.FaceDetect;
import hieuph.facerecognition.ManipulationPicture.MyImageView;
import hieuph.facerecognition.ManipulationPicture.PictureUtility;
import hieuph.facerecognition_datn.R;

import java.io.FileNotFoundException;
import java.io.IOException;

import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.objdetect.CascadeClassifier;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
	private static final String TAG = "OCVSample::Activity";

	public static final String URI_STRING = "uri";
	public static int screenHeight, screenWidth;

	MyImageView myImageView;
	SeekBar seekbarFaceSize;
	TextView tvFaceSizePercent;
	Uri imageURI = null;
	private boolean isViewInfo = false;
	
	// int progressValue;
	private CascadeClassifier mJavaDetector;
	FaceDetect mFaceDetect;

	private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
		@Override
		public void onManagerConnected(int status) {
			switch (status) {
			case LoaderCallbackInterface.SUCCESS: {
				Log.i(TAG, "OpenCV loaded successfully");

				try {
					mJavaDetector = FaceDetect
							.getJavaDetector(getApplicationContext());
					if (mJavaDetector != null) {
						Toast.makeText(mAppContext, "Lay duoc JavaDetector",
								Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(mAppContext,
								"Khong lay duoc JavaDetector",
								Toast.LENGTH_SHORT).show();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					Toast.makeText(mAppContext, "" + e.getMessage(),
							Toast.LENGTH_SHORT).show();
				}
			}
				break;
			default: {
				super.onManagerConnected(status);
			}
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		myImageView = (MyImageView) findViewById(R.id.Imagefaceview);
		if (savedInstanceState != null) {
			imageURI = Uri.parse(savedInstanceState.getString(URI_STRING));
			setImage(imageURI);
		}
		tvFaceSizePercent = (TextView) findViewById(R.id.precentSize);
		seekbarFaceSize = (SeekBar) findViewById(R.id.seekbarSizeFace);
		seekbarFaceSize
				.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {

					@Override
					public void onStopTrackingTouch(SeekBar seekBar) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onStartTrackingTouch(SeekBar seekBar) {
						// TODO Auto-generated method stub

					}

					@Override
					public void onProgressChanged(SeekBar seekBar,
							int progress, boolean fromUser) {
						// TODO Auto-generated method stub
						mFaceDetect.setMinFaceSize(progress);
						tvFaceSizePercent.setText(progress + "%");
					}
				});

		// we use Display metrics to get the screen width and height.
		// we need the screen size for later use to set the image from gallery
		// on the screen.
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		screenHeight = displaymetrics.heightPixels;
		screenWidth = displaymetrics.widthPixels;

		// Khoi tao lop FaceDetect
		mFaceDetect = new FaceDetect();

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		outState.putString(URI_STRING, imageURI + "");
	}

	@Override
	public void onResume() {
		super.onResume();
		OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_3, this,
				mLoaderCallback);
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		myImageView.clearBimap();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main, menu);
		if(isViewInfo){
			menu.findItem(R.id.action_viewInfor).setVisible(false);
		}
		else {
			menu.findItem(R.id.action_normal).setVisible(false);
		}
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		switch (id) {
		case R.id.action_settings:
			return true;
		case R.id.action_openPicture:
			PictureUtility.openPicture(this);
			return true;
		case R.id.action_takePicture:
			PictureUtility.takePicture(this);
			return true;
		case R.id.action_crop_image:
			PictureUtility.performCrop(this, imageURI);
			return true;	
		case R.id.action_viewInfor:
			detetcFace(myImageView, mJavaDetector);
			isViewInfo = true;
			invalidateOptionsMenu();
			return true;
		case R.id.action_normal:
			isViewInfo = false;
			myImageView.EarseRect();
			invalidateOptionsMenu();
			return true;	
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	private void detetcFace(MyImageView img, CascadeClassifier mJavaDetector) {
		myImageView.facedetect(mFaceDetect.detectFace(myImageView,
				mJavaDetector));
	}

	public void setImage(Uri uri) {
		BitmapFactory.Options bitmapFatoryOptions = new BitmapFactory.Options();
		bitmapFatoryOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;

		try {
			Bitmap b = BitmapFactory.decodeStream(getContentResolver()
					.openInputStream(imageURI), null, bitmapFatoryOptions);
			myImageView.setImage(b);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			Toast.makeText(getApplicationContext(), e.getMessage() + "",
					Toast.LENGTH_LONG).show();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case PictureUtility.CAMERA_RETURN_CODE:
				imageURI = data.getData();
				setImage(imageURI);
//				Bitmap cameraBmp = (Bitmap) data.getExtras().get("data");
//				myImageView.setImage(cameraBmp);
				break;
			case PictureUtility.OPEN_PICTURE_RETURN_CODE:
				imageURI = data.getData();
				setImage(imageURI);
				break;
			case PictureUtility.PIC_CROP:
				// Thuc hien add vao danh sach lien lac o day
				break;
			default:
				break;
			}
		}
	}

}
